//The MIT License
//
//Copyright (c) 2009 nodchip
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.
package tv.dyndns.kishibe.client.setting;

import java.util.logging.Level;
import java.util.logging.Logger;

import tv.dyndns.kishibe.client.Service;
import tv.dyndns.kishibe.client.UserData;
import tv.dyndns.kishibe.client.packet.PacketUserData;

import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.RepeatingCommand;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

public class PanelSettingUserCode extends VerticalPanel implements ClickHandler {
	private static final Logger logger = Logger.getLogger(PanelSettingUserCode.class.getName());
	private static final int UPDATE_DURATION = 1000;
	private final TextBox textBoxUserCode = new TextBox();
	private final Button buttonChangeUserCode = new Button("ユーザーコード変更", this);
	private final HTML htmlMessage = new HTML();
	private boolean finished = false;
	private final RepeatingCommand commandUpdate = new RepeatingCommand() {
		@Override
		public boolean execute() {
			if (!finished) {
				checkUserCoder();
			}
			return isAttached();
		}
	};

	public PanelSettingUserCode() {
		setHorizontalAlignment(ALIGN_CENTER);
		add(new HTML(
				"ユーザーコードを変更できます。<br/>ユーザーコードを覚えるとどこでも自分のプレイヤー情報でプレイできます。<br/>ユーザーコードの変更後はF5を押してページのリロードをして下さい"));

		textBoxUserCode.setWidth("200px");
		add(textBoxUserCode);

		add(buttonChangeUserCode);

		htmlMessage.addStyleDependentName("settingMessage");
		add(htmlMessage);

		checkUserCoder();
	}

	private boolean checkUserCoder() {
		boolean result = true;
		try {
			Integer.parseInt(textBoxUserCode.getText());
			htmlMessage.setText("");
		} catch (Exception e) {
			result = false;
			htmlMessage.setText("ユーザーコードが正しくありません");
		}

		buttonChangeUserCode.setEnabled(result);
		return result;
	}

	private void changeUserCode() {
		if (!checkUserCoder()) {
			return;
		}

		try {
			final String userCodeString = textBoxUserCode.getText();
			final int userCode = Integer.parseInt(userCodeString);
			finished = true;
			buttonChangeUserCode.setEnabled(false);
			Service.Util.getInstance().loadUserData(userCode, callbackChangeUserCode);
		} catch (Exception e) {
			String message = "ユーザーコードが正しくありません";
			logger.log(Level.WARNING, message, e);
			htmlMessage.setText(message);
		}
	}

	private final AsyncCallback<PacketUserData> callbackChangeUserCode = new AsyncCallback<PacketUserData>() {
		public void onSuccess(PacketUserData result) {
			if (result.userCode == 0) {
				htmlMessage.setText("指定されたユーザーコードが存在しません");
				buttonChangeUserCode.setEnabled(true);
				return;
			}

			UserData.get().setUserCode(result.userCode);
			Window.alert("OKボタンを押した後にF5ボタンを押してページをリロードしてください");
		}

		public void onFailure(Throwable caught) {
			logger.log(Level.WARNING, "ユーザーコードの切り替えに失敗しました", caught);
		}
	};

	@Override
	protected void onLoad() {
		super.onLoad();
		finished = false;
		Scheduler.get().scheduleFixedDelay(commandUpdate, UPDATE_DURATION);
	}

	@Override
	public void onClick(ClickEvent event) {
		final Object sender = event.getSource();
		if (sender == buttonChangeUserCode) {
			changeUserCode();
		}
	}
}
